package com.company.learnjpa.util;

import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 *
 * @author xiaolei
 */
public class Helper {

    /**
     * 重定向
     *
     * @param target
     */
    public static void redirect(String target) {
        try {
            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
            ec.redirect(ec.getRequestContextPath() + target);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void addFlashObject(String key, Object value) {
        FacesContext.getCurrentInstance()
                .getExternalContext()
                .getFlash()
                .put(key, value);
    }

    public static Object getFlashObject(String key) {
        return FacesContext.getCurrentInstance()
                .getExternalContext()
                .getFlash()
                .get(key);
    }

    public static void addInfoMessage(String summary, String detail) {
        Helper.addMessage(FacesMessage.SEVERITY_INFO, summary, detail);
    }

    public static void addErrorMessage(String summary, String detail) {
        Helper.addMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
    }

    private static void addMessage(FacesMessage.Severity severity, String summary, String detail) {
        FacesMessage facesMessage = new FacesMessage(severity, summary, detail);
        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
    }

    public static String getFirst(String html, int size) {
        final Pattern HTML_TAG_PATTERN = Pattern.compile("<[^>]+>");
        if (html == null || html.isEmpty()) {
            return "";
        }
        // 替换所有HTML标签为空白
        String pureText = HTML_TAG_PATTERN.matcher(html).replaceAll("");
        // 清理连续空白字符（空格、换行、制表符等），替换为单个空格
        pureText = pureText.replaceAll("\\s+", " ").trim();
        return pureText.length() > size
                ? pureText.substring(0, size)
                : pureText;
    }
}
